Iterative DFS C#


  • 0
    P
    public class TreeNode
        {
            public int val;
            public int valtillnow;
            public List<int> eletillnow = new List<int>();
            public TreeNode left;
            public TreeNode right;
            public TreeNode(int x, TreeNode left, TreeNode right) { val = x; this.left = left; this.right = right; }
        }
    
            public IList<IList<int>> dfs(TreeNode tn,int total)
            {
                IList<IList<int>> ele = new List<IList<int>>();
                Stack<TreeNode> st = new Stack<TreeNode>();
                tn.valtillnow = tn.val;
                tn.eletillnow.Add(tn.val);
                st.Push(tn);
                int sum = 0;
    
                while (st.Count != 0)
                {
                    TreeNode cur = st.Pop();
                    if (cur != null)
                    {
                        if (cur.left != null) {
                            st.Push(cur.left);
                            cur.left.valtillnow = cur.valtillnow + cur.left.val;
                            cur.left.eletillnow.AddRange(cur.eletillnow);
                            cur.left.eletillnow.Add(cur.left.val);
                        }
                        if (cur.right != null) {
                            st.Push(cur.right);
                            cur.right.valtillnow = cur.valtillnow + cur.right.val;
                            cur.right.eletillnow.AddRange(cur.eletillnow);
                            cur.right.eletillnow.Add(cur.right.val);
                        }
                        if (cur.left == null && cur.right == null)
                        {
                            sum += cur.valtillnow;
                            if (sum == total)
                                ele.Add(cur.eletillnow);
                        }
                    }
                }
                return ele;
            }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.